#!/bin/sh
#
# $Id$
#
# opensips control tool for maintaining opensips
#
#===================================================================

PATH=$PATH:/usr/local/sbin/

# for testing only, please don't enable this in production environments
# as this introduce security risks
TEST=${TEST:-"false"}
### include config files
if [ -n "$osipsctlrc" -a -f "$osipsctlrc" ]; then
	. "$osipsctlrc"
else
	if [ -f /etc/opensips/opensipsctlrc ]; then
		. /etc/opensips/opensipsctlrc
	fi
	if [ -f /usr/local/etc/opensips/opensipsctlrc ]; then
		. /usr/local/etc/opensips/opensipsctlrc
	fi
	if [ -f ~/.opensipsctlrc ]; then
		. ~/.opensipsctlrc
	fi

	if [ $TEST = "true" ]; then
		ETCDIR=etc/
		if [ -f ./opensipsctlrc ]; then
			. ./opensipsctlrc
		elif [ -f scripts/opensipsctlrc ]; then
			. scripts/opensipsctlrc
		fi
	fi
fi

if [ -z $SHELL_TESTED ] && [ -z $NOHLPRINT ] ; then
	if [ -x /bin/bash ]; then
		# bash is available
		export SHELL_TESTED=yes
		exec /bin/bash "$0" "$@"
	else
		NOHLPRINT=yes
	fi
fi



### force values for variables in this section
# you better set the variables in ~/.opensipsctlrc
if [ -z $ETCDIR ] ; then
	ETCDIR="/usr/local/etc/opensips"
else
	# Fix relative paths
	[ "${ETCDIR:0:1}" != "/" ] && ETCDIR=$PWD/$ETCDIR
fi

### version for this script
VERSION='$Revision: 4448 $'

if [ -z $MYDIR ] ; then
	MYDIR=`dirname $0`
fi

if [ -z $MYLIBDIR ] ; then
	MYLIBDIR="/usr/local/lib/opensips/opensipsctl"
	if [ ! -d $MYLIBDIR ]; then
		MYLIBDIR=$MYDIR
	fi
fi

##### ------------------------------------------------ #####
### load base functions
#
if [ -f "$MYLIBDIR/opensipsctl.base" ]; then
	. "$MYLIBDIR/opensipsctl.base"
else
	echo -e "Cannot load core functions '$MYLIBDIR/opensipsctl.base' - exiting ...\n"
	exit -1
fi

##### ------------------------------------------------ #####
### define default parameters that may be overridden by
### different database engines
#
now="now()"

#
##### ------------------------------------------------ #####
### DBENGINE
#
DBENGINELOADED=0
case $DBENGINE in
	MYSQL|mysql|MySQL)
		if [ -f "$MYLIBDIR/opensipsctl.mysql" ]; then
			. "$MYLIBDIR/opensipsctl.mysql"
			DBENGINELOADED=1
		fi
		;;
	PGSQL|pgsql|postgres|postgresql|POSTGRESQL)
		if [ -f "$MYLIBDIR/opensipsctl.pgsql" ]; then
			. "$MYLIBDIR/opensipsctl.pgsql"
			DBENGINELOADED=1
		fi
		;;
	ORACLE|oracle|Oracle)
		if [ -f "$MYLIBDIR/opensipsctl.oracle" ]; then
			. "$MYLIBDIR/opensipsctl.oracle"
			DBENGINELOADED=1
		fi
		;;

	DBTEXT|dbtext|textdb)
		if [ -f "$MYLIBDIR/opensipsctl.dbtext" ]; then
			. "$MYLIBDIR/opensipsctl.dbtext"
			DBENGINELOADED=1
		fi
		;;
	DB_BERKELEY|db_berkeley|BERKELEY|berkeley)
		if [ -f "$MYLIBDIR/opensipsctl.db_berkeley" ]; then
			. "$MYLIBDIR/opensipsctl.db_berkeley"
			DBENGINELOADED=1
		fi
		;;
	SQLITE|db_sqlite|SQLITE|sqlite)
	        if [ -f "$MYLIBDIR/opensipsctl.sqlite" ]; then
			. "$MYLIBDIR/opensipsctl.sqlite"
		        DBENGINELOADED=1
                        now="datetime('now','localtime')"
		fi
                ;;

esac

if [ $DBENGINELOADED -eq 1 ] ; then
	mdbg "database engine '$DBENGINE' loaded"
elif [ -n "$DBENGINE" ] ; then
	mwarn "database engine not found - tried '$DBENGINE'"
fi

#
##### ------------------------------------------------ #####
### CTLENGINE
#
CTLENGINELOADED=0
if [ -z $CTLENGINE ] ; then
	CTLENGINE="FIFO"
fi
case $CTLENGINE in
	FIFO|fifo)
		if [ -f "$MYLIBDIR/opensipsctl.fifo" ]; then
			. "$MYLIBDIR/opensipsctl.fifo"
			CTLENGINELOADED=1
		fi
		;;
	UNIXSOCK|unixsock)
		if [ -f "$MYLIBDIR/opensipsctl.unixsock" ]; then
			. "$MYLIBDIR/opensipsctl.unixsock"
			CTLENGINELOADED=1
		fi
		;;
esac

if [ $CTLENGINELOADED -eq 1 ] ; then
	mdbg "Control engine '$CTLENGINE' loaded"
else
	mwarn "no control engine found - tried '$CTLENGINE'"
fi

#
##### ------------------------------------------------ #####
### common functions
#
usage() {
	CMD=`basename $0`
	if [ "0$VERIFY_ACL" -eq 1 ] ; then
		EXTRA_TEXT="ACL privileges are: $ACL_GROUPS"
	fi
	cat <<EOF
$0 $VERSION

Existing commands:
EOF
for f in $USAGE_FUNCTIONS
do
	$f
done
	echo

}

require_dbengine() {
	if [ $DBENGINELOADED -eq 0 ] ; then 
		merr "This command requires a database engine - none was loaded"
		exit -1
	fi
}

require_ctlengine() {
	if [ $CTLENGINELOADED -eq 0 ] ; then 
		merr "This command requires a control engine - none was loaded"
		exit -1
	fi
}

#
##### ------------------------------------------------ #####
### combined functions (require db and/or ctl)
#
#

#
##### ------------------------------------------------ #####
### helper functions (require db and/or ctl)
#

lower() {
	echo $1 | tr [A-Z] [a-z]
}

# params: user
# output: false if exists, true otherwise
is_user() {
	set_user $1
	
	QUERY="select count(*) from $SUB_TABLE where \
$SUBSCRIBER_COLUMN='$OSIPSUSER' and $REALM_COLUMN='$OSIPSDOMAIN';"

	CNT=`$DBCMD "$QUERY" "$DBRAWPARAMS" | $EGREP -v ERROR | $LAST_LINE`
	mdbg "is_user: user counter=$CNT"
	if [ "$CNT" = "0" ] ; then
		false
	else
		true
	fi
}


# params: table, column, value
# output: false if exists, true otherwise
is_value_in_db() {
	TABLE=$1
	COL=$2
	VALUE=$3
	
	QUERY="select count(*) from $TABLE where $COL='$VALUE';"
	CNT=`$DBCMD "$QUERY" "$DBRAWPARAMS" | $EGREP -v ERROR | $LAST_LINE`
	mdbg "is_value_in_db: counter=$CNT"
	if [ "$CNT" = "0" ] ; then
		false
	else
		true
	fi
}

#
##### ------------------------------------------------ #####
### ACL Management
#
acl() {
	require_dbengine
	case $1 in
		show)
			if [ $# -eq 2 ] ; then
				is_user $2 
				if [ $? -ne 0 ] ; then
					mecho "Non-existent user '$2'. Still proceeding? [Y|N] "
					read answer
					if [ $answer = "y" -o $answer = "Y" ] ; then
						minfo "Proceeding with non-local user"
					else
						exit 1
					fi
				fi
				set_user $2
				CLAUSE=" WHERE $ACL_USER_COLUMN='$OSIPSUSER' AND \
					$ACL_DOMAIN_COLUMN='$OSIPSDOMAIN' "
			elif [ $# -ne 1 ] ; then
				usage_acl
				exit 1
			fi
			QUERY="select * FROM $ACL_TABLE $CLAUSE ; "
			$DBCMD "$QUERY"

			;;

		grant)
			if [ $# -lt 3 ] ; then
				usage
				exit 1
			fi
			is_user $2 
			if [ $? -ne 0 ] ; then
				mecho "Non-existent user '$2'. Still proceeding? [Y|N] "
				read answer
				if [ $answer = "y" -o $answer = "Y" ] ; then
					minfo "Proceeding with non-local user"
				else
					exit 1
				fi
			fi
			set_user $2
			shift 2
			acl_inserted=0
			while [ $# -gt 0 ] ; do

				if [ $VERIFY_ACL -eq 1 ] ; then
					found=0
					for i in $ACL_GROUPS ; do
						if [ "$1" = "$i" ] ; then
							found=1
							break
						fi
					done
					if [ $found -eq 0 ] ; then
						mwarn "Invalid privilege: acl '$1' ignored"
						shift
						continue
					fi
				fi

				QUERY="insert into $ACL_TABLE ($ACL_USER_COLUMN,\
$ACL_GROUP_COLUMN,$ACL_MODIFIED_COLUMN,$ACL_DOMAIN_COLUMN ) values \
('$OSIPSUSER','$1', $now, '$OSIPSDOMAIN' );"
				$DBCMD "$QUERY"
				if [ $? -ne 0 ] ; then
					merr "acl - SQL Error"
					exit 1
				fi
				acl_inserted=1
				shift
			done

			if [ $acl_inserted -eq 1 ] ; then
				$0 acl show "$OSIPSUSER@$OSIPSDOMAIN"
			fi

			;;

		revoke)
			if [ $# -eq 3 ] ; then
				CLAUSE=" and $ACL_GROUP_COLUMN='$3' "
			elif [ $# -ne 2 ] ; then
				merr "acl - wrong number of parameters"
				usage_acl
				exit 1
			fi	

			set_user $2

			QUERY="delete from $ACL_TABLE where \
$ACL_TABLE.$ACL_USER_COLUMN='$OSIPSUSER' AND $ACL_DOMAIN_COLUMN='$OSIPSDOMAIN' \
$CLAUSE;"
			$DBCMD "$QUERY"

			$0 acl show "$2"

			;;

		*)
			merr "acl - invalid commad '$1'"
			usage_acl
			exit 1
			;;
	esac
}


#
##### ------------------------------------------------ #####
### alias management
#
check_db_alias() {
	require_dbengine

	ALIAS_DB_EXISTS=0

	QUERY="select count(*) from $DA_TABLE where $DA_ALIAS_USER_COLUMN='$1' \
and $DA_ALIAS_DOMAIN_COLUMN='$2';"
	CNT=`$DBCMD "$QUERY" | $EGREP -v ERROR | $LAST_LINE`
	mdbg "check_db_alias: alias counter=$CNT"
	if [ "$CNT" = "0" ] ; then
		ALIAS_DB_EXISTS=0
	else
		ALIAS_DB_EXISTS=1
	fi
}

#
# check for alias duplicates
#   params: user domain
#   output: false if exists, true otherwise
check_alias() {
	ALIAS_EXISTS=0

	if  [ $ENABLE_ALIASES -eq 1 ] ; then
		check_db_alias "$1" "$2"
		if [ $ALIAS_DB_EXISTS -eq 0 ] ; then
			ALIAS_EXISTS=0
		else
			ALIAS_EXISTS=1
		fi
	fi
}

# db-based aliases
alias_db() {
	if [ $# -lt 2 ] ; then
		merr "alias_db - too few parameters"
		echo
		usage_alias_db
		exit 1
	fi

	require_dbengine

	shift

	case $1 in 
		list)
			if [ $# -eq 2 ] ; then
				# print aliases for user
				check_aor "$2"
				if [ $? -ne 0 ] ; then
					merr "alias_db - <$2> is not a valid AoR (user@domain)"
					exit 1
				fi
				
				set_user $2
				
				CLAUSE="WHERE $DA_USER_COLUMN='$OSIPSUSER' AND \
$DA_DOMAIN_COLUMN='$OSIPSDOMAIN'"
				mecho "Dumping aliases for user=<$2>"
				echo
				if [ $DBENGINE = "MYSQL" ] ; then
					QUERY="SELECT CONCAT($DA_ALIAS_USER_COLUMN,\
	'@',$DA_ALIAS_DOMAIN_COLUMN) AS ALIAS FROM $DA_TABLE $CLAUSE;"
				elif [ $DBENGINE = "PGSQL" ] ; then
					QUERY="SELECT ($DA_ALIAS_USER_COLUMN || \
	'@' || $DA_ALIAS_DOMAIN_COLUMN) AS ALIAS FROM $DA_TABLE $CLAUSE;"
				fi

				mecho "Dumping aliases for user=<$2>"
				echo

				$DBCMD "$QUERY"
									# | $AWK 'BEGIN {line=0;}
									#		/^\+/ { next }
									#		{	if(line==0) print "ALIASES";
									#			else print line ")\t" $1 "@" $2;
									#			line++; }'
			elif [ $# -eq 1 ] ; then
				mecho "Dumping all aliases may take long: do you want to proceed? [Y|N] "
				read answer
				if [ $answer = "y" -o $answer = "Y" ] ; then
					mecho "Dumping all aliases..."
					echo
				else
					exit 1
				fi
				QUERY="SELECT $DA_ALIAS_USER_COLUMN, $DA_ALIAS_DOMAIN_COLUMN,\
$DA_USER_COLUMN, $DA_DOMAIN_COLUMN FROM $DA_TABLE;"
				$DBCMD "$QUERY"
					# | $AWK 'BEGIN {line=0;}
					#	/^\+/ { next }
					#	{	line++;
					#		if(line==1) print "SIP-ID               \tALIAS\n";
					#		else print $3 "@" $4 "\t" $1 "@" $2 }'
			else
				merr "alias_db - wrong number of params for command [list]"
				echo
				usage_alias_db
				exit 1
			fi

			exit $?
			;;
		show)
			if [ $# -ne 2 ] ; then
				merr "alias_db - wrong number of params for command [show]"
				usage_alias_db
				exit 1
			fi
			
			check_aor "$2"
			if [ $? -ne 0 ] ; then
				merr "alias_db - $2 is not a valid AoR (user@domain)"
				exit 1
			fi
			
			set_user $2
			
			CLAUSE="WHERE $DA_ALIAS_USER_COLUMN='$OSIPSUSER' AND \
$DA_ALIAS_DOMAIN_COLUMN='$OSIPSDOMAIN'"
			if [ $DBENGINE = "MYSQL" ] ; then
				QUERY="SELECT CONCAT($DA_USER_COLUMN,'@',$DA_DOMAIN_COLUMN) \
	AS 'SIP-ID' FROM $DA_TABLE $CLAUSE ; "
			elif [ $DBENGINE = "PGSQL" ] ; then
				QUERY="SELECT ($DA_USER_COLUMN || '@' || $DA_DOMAIN_COLUMN) \
	AS 'SIP-ID' FROM $DA_TABLE $CLAUSE ; "
			fi
	
			$DBCMD "$QUERY"
			#TMP_UUID=`sql_ro_query "$QUERY" | $AWK 'BEGIN {line=0;}
			#								/^\+/ { next } 
			#								{ line++;
			#								  if(line==2) print $1 "@" $2;}'`
			#
			#if [ "$TMP_UUID" = "" ] ; then
			#	mecho "non-existent alias <$2>"
			#	exit 1
			#fi
			#
			#echo "Details for alias <$2>"
			#echo
			#echo "SIP-ID: $TMP_UUID"
			#echo
			#exit $?
			;;
		add)
			if [ $# -ne 3 ] ; then
				usage_alias_db
				exit 1
			fi
			shift
			check_aor "$1"
			if [ $? -ne 0 ] ; then
				err "alias_db - $1 is not a valid AoR (user@domain)"
				exit 1
			fi

			check_aor "$2"
			if [ $? -ne 0 ] ; then
				err "alias_db - $2 is not a valid AoR (user@domain)"
				exit 1
			fi
			
			set_user $1
			TMP_OSIPSUSER=$OSIPSUSER
			TMP_OSIPSDOMAIN=$OSIPSDOMAIN
			set_user $2
		
			if [ $DBENGINE = "MYSQL" ] ; then
				if is_value_in_db $DA_TABLE "concat($DA_ALIAS_USER_COLUMN,$DA_ALIAS_DOMAIN_COLUMN)" "$TMP_OSIPSUSER$TMP_OSIPSDOMAIN"; then
					minfo "$TMP_OSIPSUSER alias already in $DA_TABLE table"
					exit 0
				fi
			elif [ $DBENGINE = "PGSQL" ] ; then
				if is_value_in_db $DA_TABLE "$DA_ALIAS_USER_COLUMN || $DA_ALIAS_DOMAIN_COLUMN" "$TMP_OSIPSUSER$TMP_OSIPSDOMAIN"; then
					minfo "$TMP_OSIPSUSER alias already in $DA_TABLE table"
					exit 0
				fi
			fi

			QUERY="INSERT INTO $DA_TABLE ($DA_USER_COLUMN,$DA_DOMAIN_COLUMN,\
			$DA_ALIAS_USER_COLUMN,$DA_ALIAS_DOMAIN_COLUMN) VALUES (\
			'$OSIPSUSER','$OSIPSDOMAIN','$TMP_OSIPSUSER','$TMP_OSIPSDOMAIN' );"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "alias_db - SQL Error"
				exit 1
			fi
			
			exit $?
			;;
		rm)
			if [ $# -ne 2 ] ; then
				merr "alias_db - wrong numbers of parameters"
				usage_alias_db
				exit 1
			fi
			
			shift
			
			check_aor "$1"
			if [ $? -ne 0 ] ; then
				merr "alias_db - $1 is not a valid URI"
				exit 1
			fi

			set_user $1
			CLAUSE="WHERE $DA_ALIAS_USER_COLUMN='$OSIPSUSER' AND \
$DA_ALIAS_DOMAIN_COLUMN='$OSIPSDOMAIN'"
			QUERY="DELETE FROM $DA_TABLE $CLAUSE;"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "alias_db - SQL Error"
				exit 1
			fi
			
			exit $?
			;;
			
		help)
			usage_alias_db "alone"
			;;
			
		*)
			usage_alias_db
			exit 1
			;;
	esac
} # end db-aliases


#
##### ------------------------------------------------ #####
### AVP management
#
# avp list [-T table] [-u <sip-id|uuid>]
#     [-a attribute] [-v value] [-t type] ... list AVPs
# avp add [-T table] <sip-id|uuid>
#     <attribute> <type> <value> ............ add AVP (*)
# avp rm [-T table]  [-u <sip-id|uuid>]
#     [-a attribute] [-v value] [-t type] ... remove AVP (*)

avpops() {
	require_dbengine
	if [ $# -lt 2 ] ; then
		merr "avp - too few parameters"
		minfo "see '$0 avp help'"
		exit 1
	fi
	if [ "$1" = "avp" ] ; then
		shift
	else
		merr "avp - unknown command $1"
		minfo "see '$0 avp help'"
		exit 1
	fi

	case $1 in 
		list)
			shift
			CLAUSE=""
			while [ $# -ne 0 ] 
			do
				TMP_ARG=$1
				shift
				case $TMP_ARG in 
					-T)
						if [ -z "$1" ] ; then
							merr "avp list - table name parameter missing"
							exit 1
						fi
						AVP_TABLE=$1
					;;
					-u)
						if [ -z "$1" ] ; then
							merr "avp list - user id or uuid parameter missing"
							exit 1
						fi
						is_aor "$1"
						if [ $? -eq 0 ] ; then
							set_user $1
							if [ "$CLAUSE" = "" ] ; then
								CLAUSE=" WHERE $AVP_USER_COLUMN='$OSIPSUSER' \
AND $AVP_DOMAIN_COLUMN='$OSIPSDOMAIN'"
							else
								CLAUSE="$CLAUSE AND \
$AVP_USER_COLUMN='$OSIPSUSER' AND $AVP_DOMAIN_COLUMN='$OSIPSDOMAIN'"
							fi
						else
							if [ "$CLAUSE" = "" ] ; then
								CLAUSE=" WHERE $AVP_UUID_COLUMN='$1'"
							else
								CLAUSE="$CLAUSE AND $AVP_UUID_COLUMN='$1'"
							fi
						fi				
					;;
					-a)
						if [ -z "$1" ] ; then
							merr "avp list - attribute name parameter missing"
							exit 1
						fi
						if [ "$CLAUSE" = "" ] ; then
							CLAUSE=" WHERE $AVP_ATTRIBUTE_COLUMN='$1'"
						else
							CLAUSE="$CLAUSE AND $AVP_ATTRIBUTE_COLUMN='$1'"
						fi
					;;
					-v)
						if [ -z "$1" ] ; then
							merr "avp list - value parameter missing"
							exit 1
						fi
						if [ "$CLAUSE" = "" ] ; then
							CLAUSE=" WHERE $AVP_VALUE_COLUMN='$1'"
						else
							CLAUSE="$CLAUSE AND $AVP_VALUE_COLUMN='$1'"
						fi
					;;
					-t)
						if [ -z "$1" ] ; then
							merr "avp list - type parameter missing"
							exit 1
						fi
						if [ "$CLAUSE" = "" ] ; then
							CLAUSE=" WHERE $AVP_TYPE_COLUMN='$1'"
						else
							CLAUSE="$CLAUSE AND $AVP_TYPE_COLUMN='$1'"
						fi
					;;
					*)
						merr "avp list - unknown parameter $1"
						exit 1
					;;
				esac
				shift
			done
			
			QUERY="SELECT $AVP_UUID_COLUMN,$AVP_USER_COLUMN,\
$AVP_DOMAIN_COLUMN,$AVP_ATTRIBUTE_COLUMN,$AVP_TYPE_COLUMN,$AVP_VALUE_COLUMN \
FROM $AVP_TABLE $CLAUSE;"
			mdbg "Query: $QUERY"
			mecho "Dumping AVPs"
			echo
			$DBCMD "$QUERY"
			# | $AWK 'BEGIN {line=0;}
			#		/^\+/ { next }
			#		{	if(line==0) print "##   UUID   \tUserID     \tAttribute     \tType     \tValue\n";
			#			else {
			#				ORS_BAK=ORS;
			#				ORS="";
			#				print line ")  " $1  $2 "@" $3 "\t" $4 "\t\"" $5;
			#				for (i=6;i<=NF;++i) print FS $i;
			#				ORS=ORS_BAK;
			#				print "\"";
			#			}
			#			line++;
			#		}'
			
			exit $?
			;;
			
		add)
			shift
			if [ $# -ne 4 ] ; then
				if [ $# -ne 6 ] ; then
					merr "avp add - bad number of parameters"
					exit 1
				fi
			fi
			if [ $# -eq 6 ] ; then
				if [ "$1" = "-T" ] ; then
					AVP_TABLE=$2
					shift
					shift
				else
					mecho "avp add - unknown parameter '$1'"
					exit 1					
				fi
			fi
						
			is_aor "$1"
			if [ $? -eq 0 ] ; then
				set_user $1
			else
				AVP_UUID=$1
			fi

			QUERY="INSERT INTO $AVP_TABLE \
($AVP_UUID_COLUMN,$AVP_USER_COLUMN,$AVP_DOMAIN_COLUMN,$AVP_ATTRIBUTE_COLUMN,\
$AVP_TYPE_COLUMN,$AVP_VALUE_COLUMN,$AVP_MODIFIED_COLUMN) \
VALUES ('$AVP_UUID','$OSIPSUSER','$OSIPSDOMAIN','$2',$3,'$4',NOW());"
			# echo "Query: $QUERY"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "avp add - SQL Error"
				exit 1
			else
				echo
				mecho "avp add - attribute added"
			fi
			
			exit $?
			;;

		rm)
			shift
			CLAUSE=""
			while [ $# -ne 0 ] 
			do
				TMP_ARG=$1
				shift
				case $TMP_ARG in 
					-T)
						if [ -z "$1" ] ; then
							merr "avp rm - table name parameter missing"
							exit 1
						fi
						AVP_TABLE=$1
					;;
					-u)
						if [ -z "$1" ] ; then
							merr "avp rm - user id or uuid parameter missing"
							exit 1
						fi
						is_aor "$1"
						if [ $? -eq 0 ] ; then
							set_user $1
							if [ "$CLAUSE" = "" ] ; then
								CLAUSE="WHERE $AVP_USER_COLUMN='$OSIPSUSER' \
AND $AVP_DOMAIN_COLUMN='$OSIPSDOMAIN'"
							else
								CLAUSE="$CLAUSE AND \
$AVP_USER_COLUMN='$OSIPSUSER' AND $AVP_DOMAIN_COLUMN='$OSIPSDOMAIN'"
							fi
						else
							if [ "$CLAUSE" = "" ] ; then
								CLAUSE="WHERE $AVP_UUID_COLUMN='$1'"
							else
								CLAUSE="$CLAUSE AND $AVP_UUID_COLUMN='$1'"
							fi
						fi				
					;;
					-a)
						if [ -z "$1" ] ; then
							merr "avp rm - attribute name parameter missing"
							exit 1
						fi
						if [ "$CLAUSE" = "" ] ; then
							CLAUSE="WHERE $AVP_ATTRIBUTE_COLUMN='$1'"
						else
							CLAUSE="$CLAUSE AND $AVP_ATTRIBUTE_COLUMN='$1'"
						fi
					;;
					-v)
						if [ -z "$1" ] ; then
							merr "avp rm - value parameter missing"
							exit 1
						fi
						if [ "$CLAUSE" = "" ] ; then
							CLAUSE="WHERE $AVP_VALUE_COLUMN='$1'"
						else
							CLAUSE="$CLAUSE AND $AVP_VALUE_COLUMN='$1'"
						fi
					;;
					-t)
						if [ -z "$1" ] ; then
							merr "avp rm - type parameter missing"
							exit 1
						fi
						if [ "$CLAUSE" = "" ] ; then
							CLAUSE="WHERE $AVP_TYPE_COLUMN='$1'"
						else
							CLAUSE="$CLAUSE AND $AVP_TYPE_COLUMN='$1'"
						fi
					;;
					*)
						merr "avp rm - unknown parameter $1"
						exit 1
					;;
				esac
				shift
			done
			QUERY="DELETE FROM $AVP_TABLE $CLAUSE;"
			mdbg "Query: $QUERY"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "avp rm - SQL Error"
				exit 1
			else
				echo
				mecho "avp rm - AVP(s) deleted"
			fi
			
			exit $?
			;;
			
		help)
			usage_avp
			;;
			
		*)
			merr "avp - unknown command"
			usage
			exit 1
			;;
	esac
} # end avpops()

#
##### ------------------------------------------------ #####
### cisco restart
#
cisco_restart() {
	require_ctlengine
	myhost=`get_my_host`
	RET=`$CTLCMD t_uac_dlg NOTIFY "$1" "." \
		"From: sip:daemon@$myhost" \
		"To: <$1>" "Event: check-sync" \
		"Contact: <sip:daemon@!!>" "." "." |
		head -1 `
	print_status $RET
}

#
##### ------------------------------------------------ #####
### DB operations
#
db_ops() {
	require_dbengine
	case $1 in
		exec|query)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing query parameter"
				exit 1
			fi
			$DBCMD "$1"
			;;
		roexec|roquery)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing query parameter"
				exit 1
			fi
			$DBCMD "$1"
			;;
		run)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing query parameter"
				exit 1
			fi
			eval QUERY=\$$1
			if [ -z "$QUERY" ] ; then
				merr "missing query value"
				exit 1
			fi
			$DBCMD "$QUERY"
			;;
		rorun)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing query parameter"
				exit 1
			fi
			eval QUERY=\$$1
			if [ -z "$QUERY" ] ; then
				merr "missing query value"
				exit 1
			fi
			$DBCMD "$QUERY"
			;;
		show)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing table parameter"
				exit 1
			fi
			QUERY="select * FROM $1;"
			$DBCMD "$QUERY"
			;;
		*)
			usage_db_ops
			exit 1
	esac
}

#
##### ------------------------------------------------ #####
### domain management
#
domain() {
	case $1 in
		reload)
			require_ctlengine
			$CTLCMD domain_reload
			;;
		show)
			require_ctlengine
			$CTLCMD domain_dump
			;;
		showdb)
			require_dbengine
			QUERY="select * FROM $DOMAIN_TABLE ; "
			$DBCMD "$QUERY"
			;;
		add)
			require_dbengine
			shift
			if [ $# -ne 1 ] ; then
				merr "missing domain parameter"
				exit 1
			fi
			if is_value_in_db $DOMAIN_TABLE $DO_DOMAIN_COLUMN $1; then
				minfo "$1 already in $DOMAIN_TABLE table"
				exit 0
			fi
			QUERY="insert into $DOMAIN_TABLE ($DO_DOMAIN_COLUMN, \
			$DO_LAST_MODIFIED_COLUMN) VALUES ('$1',$now);"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "domain - SQL Error"
				exit 1
			fi
			minfo "execute '$0 domain reload' to synchronize cache and database"
			;;
		rm)
			require_dbengine
			shift
			if [ $# -ne 1 ] ; then
				merr "missing domain parameter"
				exit 1
			fi
			QUERY="delete from $DOMAIN_TABLE where domain='$1';"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "domain - SQL Error"
				exit 1
			fi
			minfo "execute '$0 domain reload' to synchronize cache and database"
			;;
		*)
			usage_domain
			exit 1
	esac
}

#
##### ------------------------------------------------ #####
### address management
#
address() {
	case $1 in
		reload)
			require_ctlengine
			$CTLCMD address_reload
			;;
		dump)
			require_ctlengine
			$CTLCMD address_dump
			;;
		show)
			require_dbengine
			QUERY="select * FROM $ADDRESS_TABLE ; "
			$DBCMD "$QUERY"
			;;
		add)
			require_dbengine
			shift
			if [ $# -lt 5 ] ; then
				usage_address
				exit 1
			fi
			if is_value_in_db $ADDRESS_TABLE ip $2; then
				minfo "$2 already in $ADDRESS_TABLE table"
				exit 0
			fi
			case $5 in
				any|udp|tcp|tls|sctp|none)
					;;
				*)
					merr "unknown protocol"
					exit 1
			esac
			
			QUERY="insert into $ADDRESS_TABLE \
				($ADDRESS_GRP_COLUMN, $ADDRESS_IP_COLUMN, $ADDRESS_MASK_COLUMN, \
				$ADDRESS_PORT_COLUMN, $ADDRESS_PROTO_COLUMN) \
				VALUES ('$1', '$2', '$3', '$4', '$5');"

			CONTEXT_INFO=""
			if [ ! -z "$6" ]; then
				CONTEXT_INFO="$6"
			
				QUERY="insert into $ADDRESS_TABLE \
					($ADDRESS_GRP_COLUMN, $ADDRESS_IP_COLUMN, $ADDRESS_MASK_COLUMN, \
					$ADDRESS_PORT_COLUMN, $ADDRESS_PROTO_COLUMN, $ADDRESS_CONTEXT_INFO_COLUMN) \
					VALUES ('$1', '$2', '$3', '$4', '$5', '$CONTEXT_INFO');"
						
				PATTERN=""
				if [ ! -z "$7" ]; then
					PATTERN="$7"
				
					QUERY="insert into $ADDRESS_TABLE \
						($ADDRESS_GRP_COLUMN, $ADDRESS_IP_COLUMN, $ADDRESS_MASK_COLUMN, \
						$ADDRESS_PORT_COLUMN, $ADDRESS_PROTO_COLUMN, $ADDRESS_CONTEXT_INFO_COLUMN, $ADDRESS_PATTERN_COLUMN) \
						VALUES ('$1', '$2', '$3', '$4', '$5', '$CONTEXT_INFO', '$PATTERN');"
				fi
			fi

			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "address - SQL Error"
				exit 1
			fi
			minfo "execute '$0 address reload' to synchronize cache and database"
			;;
		rm)
			require_dbengine
			shift
			if [ $# -ne 4 ] ; then
				usage_address
				exit 1
			fi
			QUERY="delete from $ADDRESS_TABLE where $ADDRESS_GRP_COLUMN='$1' \
			      AND $ADDRESS_IP_COLUMN='$2' AND $ADDRESS_MASK_COLUMN='$3'\
			      AND $ADDRESS_PORT_COLUMN='$4';"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "address - SQL Error"
				exit 1
			fi
			minfo "execute '$0 address reload' to synchronize cache and database"
			;;
		*)
			usage_address
			exit 1
	esac
}

#
##### ------------------------------------------------ #####
### CARRIERROUTE management
#
cr() {
	require_dbengine
	require_ctlengine
	case $1 in
		show)
			mecho "cr routing tree"
			QUERY="select * FROM $ROUTE_TREE_TABLE ORDER BY $CARRIERROUTE_ROUTE_TREE_PREFIX_COLUMN; "
			$DBCMD "$QUERY"
			mecho "cr routes"
			QUERY="select * FROM $CARRIERROUTE_TABLE ORDER BY \
				$CARRIERROUTE_CARRIERROUTE_CARRIER_COLUMN,\
				$CARRIERROUTE_CARRIERROUTE_SCAN_PREFIX_COLUMN,\
				$CARRIERROUTE_CARRIERROUTE_DOMAIN_COLUMN,\
				$CARRIERROUTE_CARRIERROUTE_PROB_COLUMN;"
			$DBCMD "$QUERY"
			;;
		reload)
			$CTLCMD cr_reload_routes
			;;

		dump)
			$CTLCMD cr_dump
			;;

		addrt)
			shift
			if [ $# -ne 2 ] ; then
				merr "cr - missing route_tree"
				exit 1
			fi
			QUERY="insert into $ROUTE_TREE_TABLE
				( $CARRIERROUTE_ROUTE_TREE_PREFIX_COLUMN, \
				$CARRIERROUTE_ROUTE_TREE_CARRIER_COLUMN) \
				VALUES ($1, '$2');"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "cr - SQL Error"
				exit 1
			fi
			minfo "execute '$0 cr reload' to synchronize cache and database"
			;;

		rmrt)
			shift
			if [ $# -ne 1 ] ; then
				merr "cr - missing route_tree to be removed"
				exit 1
			fi
			QUERY="delete from $ROUTE_TREE_TABLE where $CARRIERROUTE_ROUTE_TREE_CARRIER_COLUMN='$1';"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "cr - SQL Error"
				exit 1 
			fi
			minfo "execute '$0 cr reload' to synchronize cache and database"
			;;

		addcarrier)
			shift
			if [ $# -lt 4 ] ; then
				merr "cr - too few parameters"
				exit 1
			fi
			PROB=1
			STRIP=0
			REWRITE_PREFIX=
			REWRITE_SUFFIX=
			COMMENT=
			FLAGS=0
			MASK=0
			if [ $# -gt 4 ] ; then
				PROB=$5
				if [ $# -gt 5 ] ; then
					STRIP=$6
					if [ $# -gt 6 ] ; then
						REWRITE_PREFIX=$7
						if [ $# -gt 7 ] ; then
							REWRITE_SUFFIX=$8
							if [ $# -gt 8 ] ; then
								COMMENT=$9
								if [ $# -gt 9 ] ; then
									FLAGS=${10}
									if [ $# -gt 10 ] ; then
										MASK=${11}
									fi
								fi
							fi
						fi
					fi
				fi
			fi
			CARRIER=$1
			SCAN_PREFIX=$2
			DOMAIN=$3
			REWRITE_HOST=$4
			echo $FLAGS
			echo $MASK
			QUERY="insert into $CARRIERROUTE_TABLE \
				( $CARRIERROUTE_CARRIERROUTE_CARRIER_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_SCAN_PREFIX_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_DOMAIN_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_PROB_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_STRIP_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_REWRITE_HOST_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_REWRITE_PREFIX_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_REWRITE_SUFFIX_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_COMMENT_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_FLAGS_COLUMN, \
				$CARRIERROUTE_CARRIERROUTE_MASK_COLUMN ) \
				VALUES ($CARRIER, '$SCAN_PREFIX', '$DOMAIN', $PROB, $STRIP, \
				'$REWRITE_HOST', '$REWRITE_PREFIX', '$REWRITE_SUFFIX', '$COMMENT', \
				$FLAGS, $MASK);"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "cr - SQL Error"
				exit 1
			fi
			minfo "execute '$0 cr reload' to synchronize cache and database"
			;;

		rmcarrier)
			shift
			if [ $# -ne 3 ] ; then
				merr "cr - too few parameters"
				exit 1
			fi
			CARRIER=$1
			SCAN_PREFIX=$2
			DOMAIN=$3
			QUERY="delete from $CARRIERROUTE_TABLE where $CARRIERROUTE_CARRIERROUTE_CARRIER_COLUMN='$CARRIER' AND \
				$CARRIERROUTE_CARRIERROUTE_SCAN_PREFIX_COLUMN='$SCAN_PREFIX' AND \
				$CARRIERROUTE_CARRIERROUTE_DOMAIN_COLUMN=$DOMAIN ;"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "cr - SQL Error"
				exit 1
			fi
			minfo "execute '$0 cr reload' to synchronize cache and database"
			;;

		*)
			usage_cr
			exit 1
	esac
}


#
##### ------------------------------------------------ #####
### DISPATCHER management
#
dispatcher() {
	require_dbengine
	require_ctlengine
	case $1 in
		show)
			mecho "dispatcher gateways"
			QUERY="select * FROM $DISPATCHER_TABLE ORDER BY $DISPATCHER_SETID_COLUMN; "
			$DBCMD "$QUERY"
			;;
		addgw)
			shift
			if [ $# -lt 6 ] ; then
				merr "too few parameters"
				usage_dispatcher
				exit 1
			fi

			if [ $# -gt 6 ] ; then
				DISPATCHER_DESCRIPTION=$7
			else
				DISPATCHER_DESCRIPTION=""
			fi 

			DISPATCHER_SETID=$1
			DISPATCHER_DESTINATION=$2
			DISPATCHER_SOCKET=$3
			DISPATCHER_STATE=$4
			DISPATCHER_WEIGHT=$5
			DISPATCHER_ATTRS=$6

			QUERY="insert into $DISPATCHER_TABLE ($DISPATCHER_SETID_COLUMN, $DISPATCHER_DESTINATION_COLUMN, $DISPATCHER_SOCKET_COLUMN, $DISPATCHER_STATE_COLUMN, $DISPATCHER_WEIGHT_COLUMN, $DISPATCHER_ATTRS_COLUMN, $DISPATCHER_DESCRIPTION_COLUMN) VALUES ($DISPATCHER_SETID, '$DISPATCHER_DESTINATION', '$DISPATCHER_SOCKET', $DISPATCHER_STATE, '$DISPATCHER_WEIGHT', '$DISPATCHER_ATTRS', '$DISPATCHER_DESCRIPTION');"

			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dispatcher - SQL Error"
				exit 1
			fi

			$CTLCMD ds_reload
			;;
		rmgw)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing gateway id to be removed"
				exit 1
			fi

			QUERY="delete from $DISPATCHER_TABLE where $DISPATCHER_ID_COLUMN='$1';"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dispatcher - SQL Error"
				exit 1
			fi

			$CTLCMD ds_reload
			;;
		reload)
			$CTLCMD ds_reload
			;;

		dump)
			$CTLCMD ds_list
			;;

		*)
			usage_dispatcher
			exit 1

	esac
}

dr() {
	require_dbengine
	require_ctlengine
	case $1 in
		show)
			mecho "dr gateways"
			QUERY="select * FROM $DR_GATEWAYS_TABLE ORDER BY $DR_GATEWAYS_GWID_COLUMN; "
			$DBCMD "$QUERY"
			mecho "dr groups"
			QUERY="select * FROM $DR_GROUPS_TABLE ORDER BY $DR_GROUPS_GROUPID_COLUMN; "
			$DBCMD "$QUERY"
			mecho "dr carriers"
			QUERY="select * FROM $DR_CARRIERS_TABLE ORDER BY $DR_CARRIERS_CARRIERID_COLUMN; "
			$DBCMD "$QUERY"
			mecho "dr rules"
			QUERY="select * FROM $DR_RULES_TABLE ORDER BY $DR_RULES_GROUPID_COLUMN; "
			$DBCMD "$QUERY"
			;;

		addgw)
			shift
			if [ $# -lt 7 ] ; then
				merr "too few parameters"
				usage_dr
				exit 1
			fi

			if [ $# -gt 7 ] ; then
				DR_GATEWAYS_DESCRIPTION=$8
			else
				DR_GATEWAYS_DESCRIPTION=""
			fi 

			DR_GATEWAYS_GWID=$1
			DR_GATEWAYS_TYPE=$2
			DR_GATEWAYS_ADDRESS=$3
			DR_GATEWAYS_STRIP=$4
			DR_GATEWAYS_PRI_PREFIX=$5
			DR_GATEWAYS_ATTRS=$6
			DR_GATEWAYS_PROBE_MODE=$7

			QUERY="insert into $DR_GATEWAYS_TABLE \
				( $DR_GATEWAYS_GWID_COLUMN, $DR_GATEWAYS_TYPE_COLUMN, $DR_GATEWAYS_ADDRESS_COLUMN, $DR_GATEWAYS_STRIP_COLUMN, $DR_GATEWAYS_PRI_PREFIX_COLUMN, $DR_GATEWAYS_ATTRS_COLUMN, $DR_GATEWAYS_PROBE_MODE_COLUMN, $DR_GATEWAYS_DESCRIPTION_COLUMN ) \
				VALUES ('$DR_GATEWAYS_GWID', $DR_GATEWAYS_TYPE, '$DR_GATEWAYS_ADDRESS', $DR_GATEWAYS_STRIP, '$DR_GATEWAYS_PRI_PREFIX', '$DR_GATEWAYS_ATTRS', $DR_GATEWAYS_PROBE_MODE, '$DR_GATEWAYS_DESCRIPTION' );"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;
		rmgw)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing gateway id to be removed"
				exit 1
			fi

			QUERY="delete from $DR_GATEWAYS_TABLE where $DR_GATEWAYS_ID_COLUMN='$1';"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;

		addcr)
			shift
			if [ $# -lt 4 ] ; then
				merr "too few parameters"
				usage_dr
				exit 1
			fi

			if [ $# -gt 4 ] ; then
				DR_CARRIERS_DESCRIPTION=$5
			else
				DR_CARRIERS_DESCRIPTION=""
			fi 

			DR_CARRIERS_CARRIERID=$1
			DR_CARRIERS_GWLIST=$2
			DR_CARRIERS_FLAGS=$3
			DR_CARRIERS_ATTRS=$4

			QUERY="insert into $DR_CARRIERS_TABLE \
				( $DR_CARRIERS_CARRIERID_COLUMN, $DR_CARRIERS_GWLIST_COLUMN, $DR_CARRIERS_FLAGS_COLUMN, $DR_CARRIERS_ATTRS_COLUMN, $DR_CARRIERS_DESCRIPTION_COLUMN ) \
				VALUES ('$DR_CARRIERS_CARRIERID', '$DR_CARRIERS_GWLIST', $DR_CARRIERS_FLAGS, '$DR_CARRIERS_ATTRS', '$DR_CARRIERS_DESCRIPTION' );"
			mecho "$QUERY"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;
		rmcr)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing gateway id to be removed"
				exit 1
			fi

			QUERY="delete from $DR_CARRIERS_TABLE where $DR_CARRIERS_ID_COLUMN='$1';"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;

		addgrp)
			shift
			if [ $# -lt 3 ] ; then
				merr "too few parameters"
				usage_dr
				exit 1
			fi

			if [ $# -gt 3 ] ; then
				DR_GROUPS_DESCRIPTION=$4
			else
				DR_GROUPS_DESCRIPTION=""
			fi 

			DR_GROUPS_USERNAME=$1
			DR_GROUPS_DOMAIN=$2
			DR_GROUPS_GROUPID=$3

			QUERY="insert into $DR_GROUPS_TABLE \
				( $DR_GROUPS_USERNAME_COLUMN, $DR_GROUPS_DOMAIN_COLUMN, $DR_GROUPS_GROUPID_COLUMN, $DR_GROUPS_DESCRIPTION_COLUMN ) \
				VALUES ('$DR_GROUPS_USERNAME', '$DR_GROUPS_DOMAIN', $DR_GROUPS_GROUPID, '$DR_GROUPS_DESCRIPTION' );"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;
		rmgrp)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing gateway id to be removed"
				exit 1
			fi

			QUERY="delete from $DR_GROUPS_TABLE where $DR_GROUPS_ID_COLUMN='$1';"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;

		addrule)
			shift
			if [ $# -lt 7 ] ; then
				merr "too few parameters"
				usage_dr
				exit 1
			fi

			if [ $# -gt 7 ] ; then
				DR_RULES_DESCRIPTION=$8
			else
				DR_RULES_DESCRIPTION=""
			fi 

			DR_RULES_GROUPID=$1
			DR_RULES_PREFIX=$2
			DR_RULES_TIMEREC=$3
			DR_RULES_PRIORITY=$4
			DR_RULES_ROUTEID=$5
			DR_RULES_GWLIST=$6
			DR_RULES_ATTRS=$7

			QUERY="insert into $DR_RULES_TABLE \
				( $DR_RULES_GROUPID_COLUMN, $DR_RULES_PREFIX_COLUMN, $DR_RULES_TIMEREC_COLUMN, $DR_RULES_PRIORITY_COLUMN, $DR_RULES_ROUTEID_COLUMN, $DR_RULES_GWLIST_COLUMN, $DR_RULES_ATTRS_COLUMN, $DR_RULES_DESCRIPTION_COLUMN ) \
				VALUES ('$DR_RULES_GROUPID', '$DR_RULES_PREFIX', '$DR_RULES_TIMEREC', $DR_RULES_PRIORITY, '$DR_RULES_ROUTEID', '$DR_RULES_GWLIST', '$DR_RULES_ATTRS', '$DR_RULES_DESCRIPTION' );"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;
		rmrule)
			shift
			if [ $# -ne 1 ] ; then
				merr "missing rule id to be removed"
				exit 1
			fi

			QUERY="delete from $DR_RULES_TABLE where $DR_RULES_RULEID_COLUMN='$1';"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dr - SQL Error"
				exit 1
			fi

			$CTLCMD dr_reload
			;;

		reload)
			$CTLCMD dr_reload
			;;

		gw_status)
			$CTLCMD dr_gw_status
			;;

		carrier_status)
			$CTLCMD dr_carrier_status
			;;

		*)
			usage_dr
			exit 1

	esac
}

#
##### ------------------------------------------------ #####
### DIALPLAN management
#
dialplan() {
	require_dbengine
	require_ctlengine
	case $1 in
		show)
			shift
			if [ $# -gt 0 ] ; then
				mecho "dialplan $1 tables"
				QUERY="select * FROM $DIALPLAN_TABLE WHERE $DIALPLAN_DPID_COLUMN=$1 ORDER BY $DIALPLAN_PR_COLUMN ; "
			else
				mecho "dialplan tables"
				QUERY="select * FROM $DIALPLAN_TABLE ORDER BY $DIALPLAN_DPID_COLUMN, $DIALPLAN_PR_COLUMN; "
			fi
			$DBCMD "$QUERY"
			;;

		addrule)
			shift
			if [ $# -lt 8 ] ; then
				merr "too few parameters"
				usage_dialplan
				exit 1
			fi

			DIALPLAN_DPID=$1
			DIALPLAN_PR=$2
			DIALPLAN_MATCH_OP=$3
			case $DIALPLAN_MATCH_OP in
				equal)
					DIALPLAN_MATCH_OP=0
					;;
				regexp)
					DIALPLAN_MATCH_OP=1
					;;
				*)
					merr "dialplan - unexpected $DIALPLAN_MATCH_OP for operating matching. Use 'equal' or 'regexp'!"
					exit 1
			esac
			DIALPLAN_MATCH_EXP=$4
			DIALPLAN_MATCH_FLAGS=$5
			DIALPLAN_SUBST_EXP=$6
			DIALPLAN_REPL_EXP=$7
			DIALPLAN_ATTRS=$8

			QUERY="insert into $DIALPLAN_TABLE \
				( $DIALPLAN_DPID_COLUMN, $DIALPLAN_PR_COLUMN, $DIALPLAN_MATCH_OP_COLUMN, \
					$DIALPLAN_MATCH_EXP_COLUMN, $DIALPLAN_MATCH_FLAGS_COLUMN, \
					$DIALPLAN_SUBST_EXP_COLUMN, $DIALPLAN_REPL_EXP_COLUMN, \
					$DIALPLAN_ATTRS_COLUMN ) \
				VALUES ( $DIALPLAN_DPID, $DIALPLAN_PR, $DIALPLAN_MATCH_OP, \
					'$DIALPLAN_MATCH_EXP', $DIALPLAN_MATCH_FLAGS, '$DIALPLAN_SUBST_EXP', \
					'$DIALPLAN_REPL_EXP', '$DIALPLAN_ATTRS')";
			mecho "$QUERY"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dialplan - SQL Error"
				exit 1
			fi

			$CTLCMD dp_reload
			;;

		rm)
			QUERY="delete from $DIALPLAN_TABLE; "
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dialplan - SQL Error"
				exit 1
			fi

			$CTLCMD dp_reload
			;;

		rmdpid)
			shift
			if [ $# -lt 1 ] ; then
				merr "too few parameters"
				usage_dialplan
				exit 1
			fi

			DIALPLAN_DPID=$1

			QUERY="delete from $DIALPLAN_TABLE where $DIALPLAN_DPID_COLUMN=$DIALPLAN_DPID; "
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dialplan - SQL Error"
				exit 1
			fi

			$CTLCMD dp_reload
			;;

		rmrule)
			shift
			if [ $# -lt 2 ] ; then
				merr "too few parameters"
				usage_dialplan
				exit 1
			fi

			DIALPLAN_DPID=$1
			DIALPLAN_PR=$2

			QUERY="delete from $DIALPLAN_TABLE where $DIALPLAN_DPID_COLUMN=$DIALPLAN_DPID AND $DIALPLAN_PR_COLUMN=$DIALPLAN_PR; "
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "dialplan - SQL Error"
				exit 1
			fi

			$CTLCMD dp_reload
			;;

		reload)
			$CTLCMD dp_reload
			;;

		*)
			usage_dialplan
			exit 1

	esac
}

#
##### ------------------------------------------------ #####
### REGISTRANT management
#
registrant() {
	require_dbengine
	require_ctlengine
	case $1 in
		show)
			mecho "registrant table"
			QUERY="select * FROM $REGISTRANT_TABLE ORDER BY $REGISTRANT_AOR_COLUMN; "
			$DBCMD "$QUERY"
			;;

		dump)
			$CTLCMD reg_list
			;;

		add)
			shift
			if [ $# -lt 9 ] ; then
				merr "too few parameters"
				usage_dialplan
				exit 1
			fi

			REGISTRANT_REGISTRAR=$1
			REGISTRANT_PROXY=$2
			REGISTRANT_AOR=$3
			REGISTRANT_THIRD_PARTY_REGISTRANT=$4
			REGISTRANT_USERNAME=$5
			REGISTRANT_PASSWORD=$6
			REGISTRANT_BINDING_URI=$7
			REGISTRANT_BINDING_PARAMS=$8
			REGISTRANT_EXPIRY=$9
			REGISTRANT_FORCED_SOCKET=${10}

			QUERY="insert into $REGISTRANT_TABLE\
				( $REGISTRANT_REGISTRAR_COLUMN,\
				$REGISTRANT_PROXY_COLUMN, $REGISTRANT_AOR_COLUMN,\
				$REGISTRANT_THIRD_PARTY_REGISTRANT_COLUMN,\
				$REGISTRANT_USERNAME_COLUMN,\
				$REGISTRANT_PASSWORD_COLUMN,\
				$REGISTRANT_BINDING_URI_COLUMN,\
				$REGISTRANT_BINDING_PARAMS_COLUMN,\
				$REGISTRANT_EXPIRY_COLUMN,\
				$REGISTRANT_FORCED_SOCKET_COLUMN)\
				VALUES ( '$REGISTRANT_REGISTRAR', '$REGISTRANT_PROXY',\
				'$REGISTRANT_AOR',\
				'$REGISTRANT_THIRD_PARTY_REGISTRANT',\
				'$REGISTRANT_USERNAME', '$REGISTRANT_PASSWORD',\
				'$REGISTRANT_BINDING_URI',\
				'$REGISTRANT_BINDING_PARAMS',\
				$REGISTRANT_EXPIRY, '$REGISTRANT_FORCED_SOCKET')";
			#mecho "$QUERY"
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "registrant - SQL Error"
				exit 1
			fi

			#$CTLCMD reg_reload
			;;
		rm)
			QUERY="delete from $REGISTRANT_TABLE; "
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "registrant - SQL Error"
				exit 1
			fi

			#$CTLCMD reg_reload
			;;

		rmaor)
			shift
			if [ $# -lt 1 ] ; then
				merr "too few parameters"
				usage_registrant
				exit 1
			fi

			REGISTRANT_ID=$1

			QUERY="delete from $REGISTRANT_TABLE where $REGISTRANT_ID_COLUMN=$REGISTRANT_ID; "
			$DBCMD "$QUERY"

			if [ $? -ne 0 ] ; then
				merr "registrant - SQL Error"
				exit 1
			fi

			#$CTLCMD reg_reload
			;;
		*)
			usage_registrant
			exit 1
	esac
}

#
##### ------------------------------------------------ #####
### opensips_start
#
opensips_start() {
	echo
	minfo "Starting OpenSIPS : "
	if [ -r $PID_FILE ] ; then
		if [ -d /proc/$(cat $PID_FILE) ] ; then
			ps -ef | $EGREP opensips
			ls -l $PID_FILE
			minfo "PID file exists ($PID_FILE)! OpenSIPS already running?"
			exit 1
		else
			minfo "Removing stale PID file $PID_FILE.";
			rm -f $PID_FILE;
		fi
	fi
	
	if [ ! -x "$OSIPSBIN" ] ; then
		echo
		merr "OpenSIPS binaries not found at $OSIPSBIN"
		merr "set OSIPSBIN to the path of opensips in $0 or ~/.opensipsctlrc"
		exit 1
	fi
	if [ $SYSLOG = 1 ] ; then
		$OSIPSBIN -P $PID_FILE $STARTOPTIONS 1>/dev/null 2>/dev/null
	else
	 	$OSIPSBIN -P $PID_FILE -E $STARTOPTIONS
	fi
	sleep 3
	if [ ! -s $PID_FILE ] ; then
		echo
		merr "PID file $PID_FILE does not exist -- OpenSIPS start failed"
		exit 1
	fi
	minfo "started (pid: `cat $PID_FILE`)"
}

#
##### ------------------------------------------------ #####
### opensips_stop
#
opensips_stop() {

	# In case stop was called in restart, it should not exit.

	echo
	if [ "$1" = "restart" ]
	then
		minfo "Restarting OpenSIPS : "
	else
		minfo "Stopping OpenSIPS : "
	fi

	if [ -r $PID_FILE ] ; then
		kill `cat $PID_FILE`
		minfo "stopped"
	else
		echo
		merr "No PID file found ($PID_FILE)! OpenSIPS probably not running"
		if [ "$1" != "restart" ] ; then
			minfo "check with 'ps -ef | $EGREP opensips'"
			exit 1
		fi
	fi
}

#
##### ------------------------------------------------ #####
### options_ping
#
options_ping() {
	myhost=`get_my_host`
	require_ctlengine
	CMD="t_uac_dlg OPTIONS \"$1\" \".\" \".\" \"From:sip:daemon@$myhost"$'\r\n'"To:<$1>"$'\r\n'"Contact:sip:daemon@$myhost"$'\r\n'"\""
	RET=`$CTLCMD $CMD | head -1`
	print_status $RET
}

#
##### ------------------------------------------------ #####
### rpid management
#
rpid() {
	if [ "$#" -lt 2 ] ; then
		merr "rpid - too few parameters"
		exit 1
	fi
	shift;
	require_dbengine
	case $1 in
		show)
			if [ $# -eq 2 ] ; then
				set_user $2
				is_user $2 
				if [ $? -ne 0 ] ; then
					merr "rpid - invalid user '$2'"
					exit 1;
				fi
				CLAUSE=" WHERE $SUBSCRIBER_COLUMN='$OSIPSUSER' AND \
$REALM_COLUMN='$OSIPSDOMAIN' "
			elif [ $# -ne 1 ] ; then
				usage_rpid
				exit 1
			fi
			QUERY="select $SUBSCRIBER_COLUMN, $RPID_COLUMN FROM $SUB_TABLE \
$CLAUSE ; "
			$DBCMD "$QUERY"
			;;

		add|rm)
		    MODE=$1;

			if [ "$MODE" = "add" ] ; then
			    ARG_NUM=3;
			else
			    ARG_NUM=2;
			fi
			
			if [ $# -lt $ARG_NUM ] ; then
				usage_rpid
				exit 1
			fi

			set_user $2
			is_user $2 
			if [ $? -ne 0 ] ; then
				merr "rpid - invalid user '$2'"
				exit 1
			fi
			shift 2

			if [ "$MODE" = "add" ] ; then
			        RPID_VAL="'$1'";
			else
			        RPID_VAL=NULL;
			fi

			QUERY="UPDATE $SUB_TABLE SET $RPID_COLUMN=$RPID_VAL \
WHERE $SUBSCRIBER_COLUMN='$OSIPSUSER' AND $REALM_COLUMN='$OSIPSDOMAIN';"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "rpid - SQL Error"
				exit 1
			fi

			$0 rpid show "$OSIPSUSER@$OSIPSDOMAIN"

			;;

		*)
			usage_rpid
			exit 1
			;;
	esac
}

#
##### ------------------------------------------------ #####
### SPEEDDIAL management
#
speeddial() {
	if [ "$#" -lt 2 ] ; then
		merr "speeddial - too few parameters"
		echo
		usage_speeddial
		exit 1
	fi

	require_dbengine
	shift

	case $1 in 
		list)
			if [ $# -eq 2 ] ; then
				# print speed-dials for user
				check_aor "$2"
				if [ $? -ne 0 ] ; then
					merr "speeddial - <$2> is not a valid AoR (user@domain)"
					exit 1
				fi
				
				set_user $2
				
				CLAUSE="WHERE $SD_USER_COLUMN='$OSIPSUSER' AND \
$SD_DOMAIN_COLUMN='$OSIPSDOMAIN'"
				mecho "Dumping speed-dials for user=<$2>"
				echo
				if [ $DBENGINE = "MYSQL" ] ; then
				QUERY="SELECT CONCAT($SD_SD_USER_COLUMN,'@',\
	$SD_SD_DOMAIN_COLUMN) AS 'Short number', $SD_NEW_URI_COLUMN AS 'New URI',\
	$SD_DESC_COLUMN FROM $SD_TABLE $CLAUSE;"
				elif [ $DBENGINE = "PGSQL" ] ; then
				QUERY="SELECT ($SD_SD_USER_COLUMN || '@' || \
	$SD_SD_DOMAIN_COLUMN) AS 'Short number', $SD_NEW_URI_COLUMN AS 'New URI',\
	$SD_DESC_COLUMN FROM $SD_TABLE $CLAUSE;"
				fi
				mecho "Dumping speed-dials for user=<$2>"
				echo

				$DBCMD "$QUERY"
					#| $AWK 'BEGIN {line=0;}
					#	/^\+/ { next }
		#{ if(line==0) print "##   SpeedDial   \tNew-URI     \tDescription\n";
					#	else {
					#		ORS_BAK=ORS;
					#		ORS="";
					#		print line ")  " $1 "@" $2 "\t" $3 "\t\"" $4;
					#		for (i=5;i<=NF;++i) print FS $i;
					#		ORS=ORS_BAK;
					#		print "\"";
					#	}
					#	line++;
					#}'
			elif [ $# -eq 1 ] ; then
				mecho "Dumping all speed-dials may take long: do you want to proceed? [Y|N] "
				read answer
				if [ "$answer" = "y" -o "$answer" = "Y" ] ; then
					mecho "Dumping all speed-dials..."
					echo
				else
					exit 1
				fi
				if [ $DBENGINE = "MYSQL" ] ; then
					QUERY="SELECT CONCAT($SD_SD_USER_COLUMN,'@',\
$SD_SD_DOMAIN_COLUMN) AS 'Short number', CONCAT($SD_USER_COLUMN,'@',\
$SD_DOMAIN_COLUMN) AS 'Owner', $SD_NEW_URI_COLUMN AS 'New URI',\
$SD_DESC_COLUMN FROM $SD_TABLE;"
				elif [ $DBENGINE = "PGSQL" ] ; then
					QUERY="SELECT ($SD_SD_USER_COLUMN||'@'||\
$SD_SD_DOMAIN_COLUMN) AS 'Short number', ($SD_USER_COLUMN||'@'||\
$SD_DOMAIN_COLUMN) AS 'Owner', $SD_NEW_URI_COLUMN AS 'New URI',\
$SD_DESC_COLUMN FROM $SD_TABLE;"
				fi
				$DBCMD "$QUERY"
				#| $AWK 'BEGIN {line=0;}
				#	/^\+/ { next }
				#	{	line++;
	#if(line==1) print "SIP-ID     \tSpeedDial  \tNew-URI    \tDescritpion\n";
				#		else {
				#			ORS_BAK=ORS;
				#			ORS="";
				#			print $3 "@" $4 "\t" $1 "@" $2 "\t" $5 "\t\"" $6;
				#			for (i=7;i<=NF;++i) print FS $i;
				#			ORS=ORS_BAK;
				#			print "\"";
				#		}
				#	}'
			else
				merr "speeddial - wrong number of params for command [list]"
				usage_speeddial
				exit 1
			fi

			exit $?
			;;
		show)
			if [ $# -ne 2 ] ; then
				merr "speeddial - wrong number of params for command [show]"
				usage_speeddial
				exit 1
			fi
			
			check_aor "$2"
			if [ $? -ne 0 ] ; then
				merr "speeddial - $2 is not a valid AoR (user@domain)"
				exit 1
			fi
			
			set_user $2
			
			CLAUSE="WHERE $SD_SD_USER_COLUMN='$OSIPSUSER' AND \
$SD_SD_DOMAIN_COLUMN='$OSIPSDOMAIN'"
			if [ $DBENGINE = "MYSQL" ] ; then
				QUERY="SELECT CONCAT($SD_USER_COLUMN,'@',$SD_DOMAIN_COLUMN) \
	AS 'Owner', $SD_NEW_URI_COLUMN AS 'New URI', $SD_DESC_COLUMN FROM \
	$SD_TABLE $CLAUSE ; "
			elif [ $DBENGINE = "PGSQL" ] ; then
				QUERY="SELECT ($SD_USER_COLUMN || '@' || $SD_DOMAIN_COLUMN) \
	AS 'Owner', $SD_NEW_URI_COLUMN AS 'New URI', $SD_DESC_COLUMN FROM \
	$SD_TABLE $CLAUSE ; "
			fi
			mecho "Details for speeddial <$2>"
			$DBCMD "$QUERY"
			# | $AWK 'BEGIN {line=0;} /^\+/ { next } 
			# { 
			#	  if(line==0) print "##  SIP-ID    \tNew-URI   \tDescritpion\n";
			#	  else {
			#		  ORS_BAK=ORS;usage_opensips_monitor() {
			#		  ORS="";
			#		  print line ") " $1 "@" $2 "\t" $3 "\t\"" $4;
			#		  for (i=5;i<=NF;++i) print FS $i;
			#		  ORS=ORS_BAK;
			#		  print "\"";
			#	  }
			#	  line++;
			# }'

			exit $?
			;;
		add)
			if [ $# -ne 4 ] ; then
				if [ $# -ne 5 ] ; then
					merr "speeddial - wrong number of parameters"
					usage_speeddial
					exit 1
				fi
			fi
			shift
			check_aor "$1"
			if [ $? -ne 0 ] ; then
				merr "speeddial - $1 is not a valid AoR (user@domain)"
				exit 1
			fi

			check_aor "$2"
			if [ $? -ne 0 ] ; then
				merr "speeddial - $2 is not a valid AoR (user@domain)"
				exit 1
			fi
			
			check_sipaor "$3"
			if [ $? -ne 0 ] ; then
				merr "speeddial - $3 is not a valid SIP AoR (sip:user@domain)"
				exit 1
			fi
			
			set_user $1
			TMP_OSIPSUSER=$OSIPSUSER
			TMP_OSIPSDOMAIN=$OSIPSDOMAIN
			set_user $2
			
			QUERY="INSERT INTO $SD_TABLE ($SD_USER_COLUMN,$SD_DOMAIN_COLUMN,\
$SD_SD_USER_COLUMN,$SD_SD_DOMAIN_COLUMN,$SD_NEW_URI_COLUMN,$SD_DESC_COLUMN) \
VALUES ('$TMP_OSIPSUSER','$TMP_OSIPSDOMAIN','$OSIPSUSER','$OSIPSDOMAIN','$3','$4');"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "speeddial - SQL Error"
				exit 1
			fi
			mecho "ok - spedd dial added"
			echo
			exit $?
			;;
		rm)
			if [ $# -ne 3 ] ; then
				merr "speeddial rm - invalid number of parameters"
				usage_speeddial
				exit 1
			fi
			
			shift
			
			check_aor "$1"
			if [ $? -ne 0 ] ; then
				merr "speeddial - $1 is not a valid AoR (user@domain)"
				exit 1
			fi
			
			check_aor "$2"
			if [ $? -ne 0 ] ; then
				merr "speeddial - $2 is not a valid AoR (user@domain)"
				exit 1
			fi

			set_user $1
			TMP_OSIPSUSER=$OSIPSUSER
			TMP_OSIPSDOMAIN=$OSIPSDOMAIN
			set_user $2

			CLAUSE="WHERE $SD_USER_COLUMN='$TMP_OSIPSUSER' AND \
$SD_DOMAIN_COLUMN='$TMP_OSIPSDOMAIN' AND $SD_SD_USER_COLUMN='$OSIPSUSER' AND \
$SD_SD_DOMAIN_COLUMN='$OSIPSDOMAIN'"
			QUERY="DELETE FROM $SD_TABLE $CLAUSE;"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "speeddial - SQL Error"
				exit 1
			fi
			
			mecho "ok - spedd dial deleted"
			echo

			;;
			
		help)
			usage_speeddial
			;;
			
		*)
			merr "speeddial - unknown command"
			usage_speeddial
			exit 1
			;;
	esac
} # end speed_dial()

#
##### ================================================ #####
### subscriber management
#
subscriber() {
	if [ $# -lt 2 ] ; then
		merr "too few parameters"
		usage_subscriber
		exit 1
	fi

	require_dbengine
	
	case $1 in
		add)
			if [ $# -ne 3 ] ; then
				usage_subscriber
				exit 1
			fi
			shift
			credentials $1 $2
			is_user $1
			if [ $? -eq 0 ] ; then
				minfo "user '$1' already exists"
				exit 1
			fi
			set_user $1
			check_alias $OSIPSUSER $OSIPSDOMAIN
			if [ $ALIAS_EXISTS -eq 1 ] ; then
				minfo "user '$1' already exists as alias"
				exit 1
			fi

			if [ $STORE_PLAINTEXT_PW -eq 1 ] ; then
				PASS="$2"
			else
				PASS=""
			fi

			QUERY="insert into $SUB_TABLE ($SUBSCRIBER_COLUMN,\
				$REALM_COLUMN,$HA1_COLUMN,$HA1B_COLUMN,$PASSWORD_COLUMN) \
				values ('$OSIPSUSER','$OSIPSDOMAIN','$HA1','$HA1B','$PASS');";
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "introducing the new user '$1' to the database failed"
			else
				mecho "new user '$1' added"
			fi
			;;

		passwd)
			if [ $# -ne 3 ] ; then
				usage_subscriber
				exit 1
			fi
			shift
			credentials $1 $2

			is_user $1
			if [ $? -ne 0 ] ; then
				merr "non-existent user '$1'"
				exit 1
			fi

			if [ $STORE_PLAINTEXT_PW -eq 1 ] ; then
				PASS="$2"
			else
				PASS=""
			fi

			QUERY="update $SUB_TABLE set $HA1_COLUMN='$HA1', \
$HA1B_COLUMN='$HA1B', $PASSWORD_COLUMN='$PASS' \
WHERE $SUBSCRIBER_COLUMN='$OSIPSUSER' and $REALM_COLUMN='$OSIPSDOMAIN';"
			$DBCMD "$QUERY"
			if [ $? -ne 0 ] ; then
				merr "password change failed"
			else
				minfo "password change succeeded"
			fi
			;;

		rm)
			if [ $# -ne 2 ] ; then
				usage_subscriber
				exit 1
			fi

			require_ctlengine
			shift 

			is_user $1 
			if [ $? -ne 0 ] ; then
				merr "non-existent user '$1'"
				exit 1
			fi

			# begin with remove all user's privileges
			acl revoke $1  > /dev/null 2>&1

			# destroy db-aliases
			QUERY="delete from $DA_TABLE where $DA_USER_COLUMN='$OSIPSUSER' \
and $DA_DOMAIN_COLUMN='$OSIPSDOMAIN';"
			$DBCMD "$QUERY"


			# destroy the user now
			QUERY="delete from $SUB_TABLE where $SUBSCRIBER_COLUMN='$OSIPSUSER' \
and $REALM_COLUMN='$OSIPSDOMAIN';"
			$DBCMD "$QUERY"

			# and also all his contacts
			$0 ul rm $1   > /dev/null 2>&1
			;;
	esac

}

#
##### ================================================ #####
### USRLOC management
#
usrloc() {
	if [ $# -lt 2 ] ; then
		merr "usrloc - too few parameters"
		usage_usrloc
		exit 1
	fi

	require_ctlengine

	if [ "$1" = "ul" ] ; then
		USRLOC_TABLE="$UL_TABLE"
		if [ -z $USRLOC_TABLE ] ; then
			USRLOC_TABLE=location
		fi
		CHECK_SUB=0
	elif [ "$1" = "usrloc" ] ; then
		USRLOC_TABLE="$UL_TABLE"
		if [ -z $USRLOC_TABLE ] ; then
			USRLOC_TABLE=location
		fi
		CHECK_SUB=0
	else
		merr "usrloc - unknown subcommand '$1'"
		usage_usrloc
		exit 1
	fi
	shift

	case "$1" in 
		show)
			if [ $# -eq 2 ] ; then
				if [ "$2" = "--brief" ] ; then
					$CTLCMD ul_dump brief
				else
					set_user $2
					$CTLCMD ul_show_contact \
						$USRLOC_TABLE "$OSIPSUSER@$OSIPSDOMAIN"
				fi
			elif [ $# -eq 1 ] ; then
				$CTLCMD ul_dump
			else
				merr "wrong number of params"
				usage_usrloc
				exit 1
			fi
			exit $?
			;;
		add)
			if [ $# -eq 3 ] ; then
				# expires 0 means persistent contact
				UL_EXPIRES=0
				UL_FLAGS=0
				BR_FLAGS=0
			elif [ $# -eq 4 ] ; then
				UL_EXPIRES=$4
				UL_FLAGS=0
				BR_FLAGS=0
			else
				usage_usrloc
				exit 1
			fi
			shift
			check_uri "$2"
				
			if [ $? -ne 0 ] ; then
				merr "$2 is not a valid URI"
				exit 1
			fi

			set_user $1
			if [ $CHECK_SUB -ne 0 ] ; then
				is_user $1 
				if [ $? -eq 0 ] ; then
					merr "overlap of alias with an existing subscriber name"
					exit 1;
				fi
			fi

			check_alias $OSIPSUSER $OSIPSDOMAIN
			if [ $ALIAS_EXISTS -eq 1 ] ; then
				if [ $CHECK_SUB -ne 0 ] ; then
					minfo "alias already defined"
				else
					merr "AOR is an alias"
				fi
				exit 1
			fi

			$CTLCMD ul_add "$USRLOC_TABLE" "$OSIPSUSER@$OSIPSDOMAIN" "$2" \
"$UL_EXPIRES" "1.00" "0" "$UL_FLAGS" "$BR_FLAGS" "$ALL_METHODS"
			exit $?
			;;
		rm)
			if [ $# -eq 2 ] ; then
				shift
				set_user $1
				$CTLCMD ul_rm $USRLOC_TABLE "$OSIPSUSER@$OSIPSDOMAIN"

			elif [ $# -eq 3 ] ; then
				shift
				set_user $1
				check_uri "$2"
				if [ $? -ne 0 ] ; then
					merr "$2 is not a valid SIP URI (sip:[user@]domain)"
					exit 1
				fi

				$CTLCMD ul_rm_contact $USRLOC_TABLE "$OSIPSUSER@$OSIPSDOMAIN" "$2"

			else
				merr "wrong number of params"
				usage_usrloc
				exit 1
			fi
			;;

		*)
			usage_usrloc
			exit 1
			;;
	esac
}

##### ================================================ #####
### TLS CA management
#

tls_ca() {

	if [ "$1" = "rootCA" ] ; then
		if [ -z $2 ] ; then
			# use default
			CA_BASE=$ETCDIR/tls
		else
			CA_BASE=`(cd $2;pwd)`
		fi

		if [ ! -d $CA_BASE ] ; then
			merr "Config directory ($CA_BASE) does not exist"
			exit 1
		fi

		CA_CONF='ca.conf'
		CA_PATH=$CA_BASE/rootCA
		if [ ! -f $CA_BASE/$CA_CONF  ] ; then
			merr "root CA config file ($CA_BASE/$CA_CONF) does not exist"
			exit 1
		fi

		if [ -d $CA_PATH ] ; then
			mwarn "root CA directory ($CA_PATH) exists! Remove it (y/n)?"
			read X
			if [ "$X" != "y" -a "$X" != "Y" ] ; then
				exit 1
			fi
		fi

		mecho "Creating directory $CA_PATH and its sub-tree"
		mkdir -p $CA_PATH
		if [ $? -ne 0 ] ; then
			merr "Failed to create root directory $CA_PATH"
			exit 1
		fi
		rm -fr $CA_PATH/*
		mkdir $CA_PATH/private
		mkdir $CA_PATH/certs
		touch $CA_PATH/index.txt
		echo 01 >$CA_PATH/serial

		mecho "Creating CA self-signed certificate"
		( cd $CA_PATH; openssl req -config $CA_BASE/$CA_CONF -x509 -newkey \
			rsa:2048 -days 365 -out ./cacert.pem -outform PEM )
		if [ $? -ne 0 ] ; then
			merr "Failed to create self-signed certificate"
			exit 1
		fi

		mecho "Protecting CA private key"
		chmod 600 $CA_PATH/private/cakey.pem

		mecho "DONE"
		minfo "Private key can be found in $CA_PATH/private/cakey.pem"
		minfo "Certificate can be found in $CA_PATH/cacert.pem"

	elif [ "$1" = "userCERT" ] ; then

		if [ -z $2 ] ; then
			merr "Missing user name parameter"
			exit 1
		fi

		if [ -z $3 ] ; then
			# use default
			CA_BASE=$ETCDIR/tls
		else
			CA_BASE=`(cd $3;pwd)`
		fi

		if [ ! -d $CA_BASE ] ; then
			merr "Config directory ($CA_BASE) does not exist"
			exit 1
		fi

		USER_DIR=$CA_BASE/$2
		USER_CFG=$CA_BASE/$2.conf
		USER=$2
		REQ_CFG=$CA_BASE/request.conf

		if [ ! -f $USER_CFG ] ; then
			merr "User config file $USER_CFG not found"
			exit 1
		fi

		if [ ! -f $REQ_CFG ] ; then
			merr "Request config file $REQ_CFG not found"
			exit 1
		fi

		mecho "Using config file $USER_CFG"

		if [ -d $USER_DIR ] ; then
			mwarn "User CERT directory ($USER_DIR) exists! Remove it (y/n)?"
			read X
			if [ "$X" != "y" -a "$X" != "Y" ] ; then
				exit 1
			fi
		fi

		mecho "Creating directory $USER_DIR"
		mkdir -p $USER_DIR
		if [ $? -ne 0 ] ; then
			merr "Failed to create user directory $USER_DIR "
			exit 1
		fi
		rm -fr $USER_DIR/*

		mecho "Creating user certificate request"
		openssl req  -config $USER_CFG -out $USER_DIR/$USER-cert_req.pem \
			-keyout $USER_DIR/$USER-privkey.pem -new -nodes
		if [ $? -ne 0 ] ; then
			merr "Failed to generate certificate request"
			exit 1
		fi

		mecho "Signing certificate request"
		( cd $CA_BASE ; openssl ca -config $REQ_CFG -in \
			$USER_DIR/$USER-cert_req.pem -out $USER_DIR/$USER-cert.pem )
		if [ $? -ne 0 ] ; then
			merr "Failed to generate certificate request"
			exit 1
		fi

		mecho "Generating CA list"
		cat $CA_BASE/rootCA/cacert.pem >> $USER_DIR/$USER-calist.pem

		mecho "DONE"
		minfo "Private key is locate at $USER_DIR/$USER-privkey.pem "
		minfo "Certificate is locate at $USER_DIR/$USER-cert.pem "
		minfo "CA-List is locate at $USER_DIR/$USER-calist.pem "

	else
		[ -n "$1" ] && merr "unknown TLS command: \"$1\""
		usage_tls
		exit 1
	fi
}

##### ================================================ #####
### trap with gdb opensips processes
#

opensips_trap() {
	if [ -z "$GDB" ] ; then
		merr "'gdb' tool not found: set GDB variable to correct tool path"
		exit
	fi
	DATE=$(/bin/date +%Y%m%d_%H%M%S)
	LOG_PATH=/tmp
	LOG_FILE=$LOG_PATH/gdb_opensips_$DATE
	PID_FILE=$LOG_PATH/gdb_opensips_pid
	>$LOG_FILE

	if [ -z "$TRAP_PIDS" ]; then
		# we cannot timeout a shell function -- run it as a subshell
		($CTLCMD ps >$LOG_FILE; rm $PID_FILE) &
		ctlpid=$!
		echo $ctlpid >$PID_FILE
		(sleep 1.5; if [ -e $PID_FILE ]; then pkill -P $ctlpid; fi) &>/dev/null &
		killerpid=$!
		wait $ctlpid
		pkill -P $killerpid

		if [ $(stat -c %s $LOG_FILE) -eq 0 ]; then
			# all failed - one last desperate attempt at obtaining the pids
			echo "opensipsctl 'ps' command timed out!"
			osips_pids=($(pidof opensips | xargs -n1 | sort -n))
		else
			osips_pids=($(sed -e 's/.*PID=\([0-9]*\).*/\1/' $LOG_FILE))
		fi
	else
		osips_pids=($(echo $TRAP_PIDS | xargs -n1 | sort -n))
	fi

	minfo "Trapping OpenSIPS with gdb: "

	jobs=()
	for pid in ${osips_pids[@]}; do
		[ ! -r /proc/$pid ] && echo -n "(Bad pid: $pid) " && continue
		BIN=$(readlink -f /proc/$pid/exe)

		procline=$(ps --no-headers -ww -fp $pid)
		echo -n "$pid "
		echo "---start $pid ($procline)" >$LOG_FILE.$pid
		$GDB $BIN $pid -batch --eval-command="bt full" 2>&1 >>$LOG_FILE.$pid &
		jobs+=($!)
	done; echo

	for job in ${jobs[@]}; do wait $job; done

	for file in $(find $LOG_PATH -name $(basename $LOG_FILE).* | sort -t. -k2n); do
		cat $file >>$LOG_FILE
		echo >>$LOG_FILE
		rm $file
	done

	minfo "Success! Trap file: $LOG_FILE"
}

#
##### ================================================ #####
### main command switch
#
case $1 in
	acl)
		shift
		acl "$@"
		;;

	add)
		subscriber "$@"
		;;

	passwd)
		subscriber "$@"
		;;

	rm)
		subscriber "$@"
		;;

	ul|usrloc)
		usrloc "$@"
		;;

	alias_db|aliasdb)
		alias_db "$@"
		;;
		
	avp)
		avpops "$@"
		;;

	cisco_restart)
		if [ $# -ne 2 ] ; then	
			usage_cisco_restart
			exit 1
		fi
		cisco_restart $2
		;;

	db)
		shift
		db_ops "$@"
		;;

	showdb|userdb)
		usage
		exit 1
		;;

	domain)
		shift
		domain "$@"
		;;

	address)
		shift
		address "$@"
		;;

	fifo|unixsock)
		require_ctlengine
		shift
		$CTLCMD "$@"
		;;

	cr)
		shift
		cr "$@"
		;;

	dispatcher)
		shift
		dispatcher "$@"
		;;

	dr)
		shift
		dr "$@"
		;;

	dialplan)
		shift
		dialplan "$@"
		;;

	registrant)
		shift
		registrant "$@"
		;;

	monitor|console|moni|con)
		require_ctlengine
		$OPENSIPS_MONITOR "$@"
		;;

	online)
		require_ctlengine
		$CTLCMD ul_dump | $EGREP -i aor | awk '{print $2}' | sort | sort -mu
		exit $?
		;;

	ping)
		# error handling is hacked -- filter_fl should not
		# consume positive status -- that should be done by
		# calling app
		if [ $# -ne 2 ] ; then
			usage_ping
			exit 1
		fi
		options_ping $2
		;;

	ps)
		require_ctlengine
		$CTLCMD ps
		;;

	restart)
		opensips_stop restart
		sleep 2
		opensips_start
		;;
	
	rpid)
		rpid "$@"
		;;

	speeddial|speed_dial)
		speeddial "$@"
		;;

	tls)
		shift
		tls_ca "$@"
		;;

	trap)
		require_ctlengine
		opensips_trap
		;;

	start)
		opensips_start
		;;

	stop)
		opensips_stop
		;;

	version)
		echo  "$0 $VERSION"
		;;

	*)
		merr "$0: Unknown command - \"$1\""
		usage
		exit 1
		;;
esac

